﻿using System;

namespace yunio.websocket
{
    using WebSocket4Net;
    public class YunioWebSocket
    {
        public delegate YunioWebSocketConfig ConfigFn(YunioWebSocketConfig config);
        // 只读
        public static IYunioWsClient Listen(string uri, YunioOnMessage on_message, ConfigFn fn_config = null)
        {
            var cfg = new YunioWebSocketConfig();
            if(fn_config != null) cfg = fn_config(cfg);
            if (on_message == null) throw new ArgumentNullException(nameof(on_message));

            var ws = new WebSocket(uri);
            ws.ReceiveBufferSize = cfg.ReadBufferSize;
            ws.AutoSendPingInterval = cfg.AutoPingInterval;
            ws.MessageReceived += (sender, e) =>  on_message?.Invoke(YunioData.New(e.Message));
            ws.Open();
            return ws;
        }
        // 只读
        public static IYunioWsClient Listen(string uri, YunioParam param, YunioOnMessage on_message, ConfigFn fn_config = null)
        {
            var cfg = new YunioWebSocketConfig();
            if (fn_config != null) cfg = fn_config(cfg);
            if (on_message == null) throw new ArgumentNullException(nameof(on_message));
            helper.uri_add_param(ref uri, param);

            var ws = new WebSocket(uri);
            ws.ReceiveBufferSize = cfg.ReadBufferSize;
            ws.AutoSendPingInterval = cfg.AutoPingInterval;
            ws.MessageReceived += (sender, e) => on_message?.Invoke(YunioData.New(e.Message));
            ws.Open();
            return ws;
        }
    }
}
